<?php 
namespace  app\command\controller;

use common\bot\LoginService;
use common\model\sell66\UserOrder;
use common\model\sell66\UserOrderDetail;
use common\service\InvService;
use common\service\TradeOfferService;
use common\model\sell66\Bot as BotModel;
use common\service\QueueService;
use common\service\UserService;
use common\libs\Curl;
use common\service\MailService;
use common\service\SteamService;
use common\model\sell66\SystemLimitConfig;
use common\model\sell66\User;
use common\libs\StringHelper;
use common\service\SmsService;
class Bot{
	
	
	private function initRobot($botId){
		$bot = BotModel::get($botId);
		if(empty($bot)){
			return false;
		}
		$botId = $bot['steam_account'];
		$robot = LoginService::getInstance()->getBot($botId);
		return $robot;
	}
	

	/**
	 * 更新机器人收货订单
	 */
	public function updateOrderTraderOffer(){
		echo 'start .....';
		$orderModel = new UserOrder();
		$order = $orderModel->getOneTradingOrder();
		if(empty($order)){
			echo "wait new order into \n";
			exit;
		}
		$bot = BotModel::find($order['bot_id']);
		$apiKey = $bot['apikey'];
		var_dump( $order['tradeoffer_id'], $order['steam_id']);
		
		$tradeOffer = SteamService::getInstance()->getTradeoffer($apiKey, $order['tradeoffer_id']);
		
		if(empty($tradeOffer)){
			echo "miss steam get trade offer";
			$order->unlock();
			exit;
		}
		$tradeOfferStatus = $tradeOffer['trade_offer_state'];

		if ($tradeOfferStatus == UserOrder::$tradeOfferStatusMap['hang_up']) {
			UserOrder::updateUserOrderEscrowDate($order['user_order_id'], $tradeOffer['escrow_end_date']);
		}

		if($tradeOfferStatus == UserOrder::$tradeOfferStatusMap['create']){
			if(time() - $order['created_time'] > 300){
				SteamService::getInstance()->cancelTradeById($apiKey, $order['tradeoffer_id']);
			}
			echo "wait mark sure";
			$order->unlock();
			exit;
		}
		$status = UserOrder::updateOrderStatusByTraderOfferStatus($order,$tradeOfferStatus);
		
		if(is_array($status) && $status['code'] === true){//交易成功 后重置用户库存的缓存 
			$order->unlock();
			echo "order success \n";

			$timeScope = StringHelper::getDayTimeScope();
			$totalAmount = UserOrder::getUserOrderTotalAmount($order['user_id'], $timeScope['startTime'], $timeScope['endTime']);
			$dailyLimitConfig = SystemLimitConfig::getSystemLimitConfig('daily_limit');
			$dailyTotalLimitConfig = SystemLimitConfig::getSystemLimitConfig('daily_total_limit');
			if (($dailyLimitConfig && $order['price'] > $dailyLimitConfig['money'])
				|| ($dailyTotalLimitConfig && $totalAmount > $dailyTotalLimitConfig['money'])) {
				$res = User::updateUserLimitStatus($order['user_id'], User::$limitStatusMap['auditing']);
				if ($res) {
					SmsService::getInstance()->sendSms("海龟回收", "SMS_109465279","13261662717");
					echo 'the user orders exceeds the limit, user_id: '.$order['user_id']."\r\n";
				}
			}

			$appIds = [];
			foreach($order->orderdetails as $detail){
				if(!in_array($detail['app_id'],$appIds)){
					$appIds[] = $detail['app_id'];
				}
			}

			foreach ($appIds as $appId){
				InvService::getInstance()->resetUserInventoryStatus($order['steam_id'], $appId);
			}
			$type = 'publish';
			$to = $order['steam_id'];
			$content = $order['orderno'].':ok';
			//TradeOfferService::getInstance()->sendOkMessage($type, $to, $content);
			$payWay = $status['payWay'];
			if(getenv('queue_open') == 1){
				$data = array('user_id'=>$order['user_id'],'price'=> $order['price'],'payWay'=>$payWay);
				QueueService::getInstance()->orderSuccess($data);
			}else{
				UserService::getInstance()->userSendEmail($order['user_id'],1, $order['price'], $payWay);
			}
		}elseif($status=='cannel'){
			if(getenv('queue_open') == 1){
				$data = array('user_id'=>$order['user_id']);
				QueueService::getInstance()->orderCancel($data);
			}
//			else{
//				UserService::getInstance()->userSendEmail($order['user_id'],2);
//			}
			$type = 'publish';
			$to = $order['steam_id'];
			$content = $order['orderno'].':cannel';
			//TradeOfferService::getInstance()->sendOkMessage($type, $to, $content);
			echo "trade offer cannel";
		}
		$order->unlock();
		exit;
	}
	
	
	/**
	 * 初始化apiKey
	 */
	public function initBotApikey(){
		$botConfigs = BotModel::getAllBotSettings();
		foreach($botConfigs as $config){
			if(!empty($config['apiKey'])){
				echo $config['botId']."  apikey has init \n";
				continue;
			}
			LoginService::getInstance()->initApiKey($config);
			echo  $config['botId']." init apikey success \n";
		}
	}
	
	
	public function autoLoginBots($botId = 0){
		$botConfigs = [];
		if($botId == 0){
			$botConfigs = BotModel::getAllBotSettings(true);
		}else{
			$bot = BotModel::getOneBotSettings($botId);
			if(empty($bot)){
				echo "no any bot need login \n";die;
			}else{
				$botConfigs[]= $bot;
			}
		}
		if(empty($botConfigs)){
			echo "no any bot need login \n";die;
		}
		
		foreach ($botConfigs as $config){
			echo $config['botId']."start login\n";
			$robot = LoginService::getInstance()->dologin($config);
			if($robot){
				echo $config['botId']." login success \n";
			}else{
				echo $config['botId']." login failed \n";
			}
			sleep(120);
		}
	}
}
?>